<template>
  <div
    v-if="dialogVisible"
    class="custom-dialog"
    :modal="false"
    :style="{ 'margin-left': 'auto', 'margin-right': 0, right: 0 }"
    :close-on-click-modal="false"
  >
    <el-form
      ref="ruleFormRef"
      :rules="rules"
      :model="formAsid"
      status-icon
      label-position="right"
      label-width="100px"
    >
      <!-- <el-form-item label="id:" prop="id">
        <el-input disabled placeholder="系统自动生成" v-model="formAsid.id"></el-input>
      </el-form-item> -->

      <el-form-item label="编码:" prop="code">
        <el-input disabled placeholder="系统自动生成" v-model="formAsid.code"></el-input>
      </el-form-item>
      <el-form-item label="名称:" prop="name">
        <el-input v-model="formAsid.name"></el-input>
      </el-form-item>
      <el-form-item label="状态:" prop="status">
        <el-select
          v-model="status"
          size="medium"
          style="width: 180px"
          clearable
          @change="clickOrganizationIsdel()"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="上级业务类型:" prop="parentId">
        <el-cascader
          v-model="parentIdValue"
          :options="parentIdOptions"
          :props="props"
          @change="handleChange"
          clearable
          :show-all-levels="false"
        />
      </el-form-item>
      <!-- <el-form-item label="父级ID:" required>
        <el-input v-model="formAsid.parentId"></el-input>
      </el-form-item> -->
      <el-form-item label="级次:" prop="level">
        <el-input
          disabled
          placeholder="由业务类型带出"
          v-model="formAsid.level"
        ></el-input>
      </el-form-item>
      <!-- <el-form-item label="组织类型:" required>
        <el-select v-model="value" size="large" style="width: 240px" clearable>
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item> -->

      <el-form-item label="说明:" prop="description">
        <el-input v-model="formAsid.description"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)" v-if="showInsertButton"
          >提交</el-button
        >
        <el-button
          type="primary"
          @click="updateAside(ruleFormRef)"
          v-if="!showInsertButton"
          >修改</el-button
        >
        <el-button @click="resetForm(ruleFormRef)">清除</el-button>
        <el-button type="danger" @click="deleteAside" v-if="!showInsertButton"
          >删除</el-button
        >
      </el-form-item>
    </el-form>
  </div>
  <el-container>
    <el-header height="65px" :style="{ 'border-bottom': '1px solid #ccc' }">
      <!-- 头部按钮 -->
      <el-row type="flex" justify="end" style="background-color: rgb(211, 227, 253)">
        <div>
          <el-button @click="inseartAdminUser" type="success"> 新增</el-button>
        </div>
        <!-- <div class="title">需求汇总统计表</div> -->
      </el-row>
      <div
        style="
          margin-left: 6rem;
          height: 30px;
          background: rgb(241, 244, 243);
          margin-bottom: 0;
          position: relative;
          display: flex;
          justify-content: flex-start;
        "
      >
        <el-input
          v-model="filterText"
          style="width: 240px"
          placeholder="请输入业务类型"
        />
      </div>
    </el-header>

    <el-container>
      <el-aside
        width="12.5rem"
        :style="{
          'z-index': '1',
          'min-width': '12.5rem',
          height: dynamicHeight + 'px',
          'max-height': dynamicHeight + 'px',
          'overflow-y': 'auto',
          'margin-left': '6rem',
          'border-right': '1px solid #ccc',
        }"
      >
        <!-- style="background: linear-gradient(to right, #f7faff, #ecf9ff)" -->
        <!-- 侧边树状 -->
        <div class="down-tree">
          <el-scrollbar>
            <el-tree
              ref="treeRef"
              class="filter-tree"
              style="max-width: 300px"
              :data="data"
              :props="defaultProps"
              @node-click="handleNodeClick"
              :filter-node-method="filterNode"
            />
          </el-scrollbar>
        </div>
      </el-aside>
      <el-container>
        <el-main style="padding: 2px 2px 0 2px">
          <el-table
            v-loading="loading"
            ref="table"
            :data="tableData"
            border
            stripe
            :cell-style="cellStyle"
            :header-cell-style="headerCellStyle"
            @selection-change="handleSelectionChange"
            @row-dblclick="handleRowClick"
            @row-click="RowClick"
            :row-style="rowState"
            :row-key="(row:any) => row.id"
            :max-height="screenHeight"
            :height="screenHeight"
            :max-width="'300px'"
          >
            <el-table-column fixed type="index" width="60" align="center" />
            <el-table-column fixed type="selection" width="50" align="center" />
            <!-- <el-table-column fixed prop="id" label="id" width="70" align="center" /> -->
            <el-table-column prop="code" label="编码" width="70" align="center" />
            <el-table-column prop="name" label="名称" width="150" align="center" />
            <el-table-column prop="level" label="级次" width="90" align="center" />
            <!-- <el-table-column prop="parentId" label="父级ID" width="90" align="center" /> -->
            <el-table-column prop="isLeaf" label="是否末级" width="90" align="center" />
            <el-table-column prop="status" label="状态" width="90" align="center" />
            <el-table-column prop="description" label="说明" align="center" />
          </el-table>
        </el-main>
        <el-footer style="height: 20px">
          <div class="demo-pagination-block">
            <el-pagination
              v-model:current-page="page"
              v-model:page-size="limit"
              :page-sizes="[50, 500, 1000, 1500, 2000, 8000]"
              :small="true"
              :background="true"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            /></div
        ></el-footer>
      </el-container>
      <el-aside width="20%" :style="{ 'border-left': '1px solid #ccc' }"></el-aside>
    </el-container>
  </el-container>
</template>
<script setup lang="ts">
import {
  ref,
  watch,
  reactive,
  onMounted,
  onBeforeMount,
  computed,
  nextTick,
  onUnmounted,
  toRefs,
} from "vue";
import { Delete, Edit, Search, Share, Upload, Calendar } from "@element-plus/icons-vue";
import {
  ElButton,
  ElDialog,
  dialogEmits,
  ElMessage,
  ElTable,
  TableColumnCtx,
  ElMessageBox,
} from "element-plus";
import type { FormInstance, FormRules } from "element-plus";

import { CircleCloseFilled } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import axios from "../../axios/axiosInstance.ts";
import Cookies from "js-cookie";
import { format } from "date-fns";
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
// crud封装组件
import * as crud from "../../components/utils/crud.ts";
import SearchTableDialog from "@/components/dialogs/SearchTableDialog.vue";

// 权限控制
const searchButtonPermissionsA = ref(false);
const menuId = ref(0);
const buttonVariables = {
  searchButtonPermissionsA,
};
const selectPermissionsButton = () => {
  const userName = Cookies.get("userName");
  axios({
    url: "/select/Permissions/Button",
    method: "post",
    data: {
      userName: userName,
      menuId: menuId.value,
    },
  }).then((res) => {
    res.data.forEach((button) => {
      const buttonName = button.buttonName;
      if (buttonVariables.hasOwnProperty(buttonName)) {
        buttonVariables[buttonName].value = true;
      }
    });
  });
};
selectPermissionsButton();
//权限结束
const value = ref("");

// const options = reactive([
//   {
//     value: "Option1",
//     label: "Option1",
//   },
// ]);

// const transformResToOptions = (res) => {
//   return res.map((item) => {
//     return {
//       value: item.code,
//       label: item.codeName,
//     };
//   });
// };
// const selectSystem_parameter_sub_tableDate = reactive({
//   tableName: "BusinessDepartmentTypeMappingTable",
//   field: "organizationType",
// });
// 查询下拉框
// const selectSystem_parameter_sub_table = async () => {
//   try {
//     const res = await crud.fetchData(
//       "/BusinessType/select/System_parameter_sub_table",
//       "post",
//       selectSystem_parameter_sub_tableDate
//     );
//     options.splice(0, options.length, ...transformResToOptions(res));
//   } catch (error) {
//     console.error("请求失败:", error);
//   }
// };
// selectSystem_parameter_sub_table();
const tableData = ref([]);
const loading = ref(false);
const page = ref(1);
const status = ref("");
const limit = ref(50);
const total = ref(50);
const dialogVisible = ref(true);
const showInsertButton = ref(true);
// const displayedDepartmentID = ref("");
// const displayedPersonnelID = ref("");
// 表单规则
interface RuleForm {
  id: string;
  code: string;
  name: string;
  description: string;
  status: boolean;
  level: string;
  parentId: string;
  isLeaf: boolean;
}
const ruleFormRef = ref<FormInstance>();

const formAsid = ref<RuleForm>({
  id: "",
  code: "",
  name: "",
  description: "",
  status: true,
  level: "",
  parentId: "",
  isLeaf: false,
} as any);
// 规则
const rules = reactive<FormRules<RuleForm>>({
  name: [{ required: true, message: "请输入业务名称", trigger: "blur" }],
  parentIdValue: [{ required: true, message: "请选择上级业务", trigger: "blur" }],
});
const selectedRows = ref([]);
const apiUrl = reactive("/add/ParameterClassification");
const requestDataAsid = computed(() => ({
  formAsid: formAsid.value,
}));
const clickOrganizationIsdel = () => {
  formAsid.value.isdel = isdel.value;
};
const options = reactive([
  {
    value: "1",
    label: "启用",
  },
  {
    value: "0",
    label: "未启用",
  },
  {
    value: "-1",
    label: "停用",
  },
]);
const deleteAside = async () => {
  try {
    const res = await crud.sendRequest(
      "/delete/ ParameterClassification",
      "post",
      requestDataAsid.value
    );
    selectBusinessMatterClassificationAside();
    selectBusinessMatterClassification();
    resetForm();
  } catch (error) {
    console.error("请求失败:", error);
  }
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formAsid.value.status = formAsid.value.isLeaf ? "0" : "1";

  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        const res = await crud.sendRequest(apiUrl, "post", requestDataAsid.value);
        selectBusinessMatterClassificationAside();
        selectBusinessMatterClassification();
        resetForm();
      } catch (error) {
        console.error("请求失败:", error);
      }
    } else {
    }
  });
};
const updateAside = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formAsid.value.status = status.value;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        const res = await crud.sendRequest(
          "/update/ParameterClassification",
          "post",
          requestDataAsid.value
        );
        selectBusinessMatterClassificationAside();
        selectBusinessMatterClassification();
        resetForm();
      } catch (error) {
        console.error("请求失败:", error);
      }
    } else {
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  parentIdValue.value = "";
  if (!formEl) return;
  formEl.resetFields();
};

const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
  if (selectedRows.value.find((selectedRow) => selectedRow.id === row.id)) {
    if (column.property === "description" || column.property === "name") {
      return {
        backgroundColor: "#DFF0DB !important",
        borderColor: "#B9C9C7",
        padding: "4px",
        textAlign: "left",
      };
    }
    return {
      backgroundColor: "#DFF0DB !important",
      borderColor: "#B9C9C7",
      padding: "4px",
    };
  } else {
    if (column.property === "description" || column.property === "name") {
      return {
        padding: "4px",
        textAlign: "left",

        margin: 0,
        borderColor: "#B9C9C7",
      };
    }
    return { borderColor: "#B9C9C7", padding: "4px", margin: 0 };
  }
};
const headerCellStyle = {
  borderColor: "#B9C9C7",
  backgroundColor: "#F2F4FA", // 表头背景颜色
  fontWeight: "bold", // 表头文字粗细
  color: "#1F2129",
};

const handleSelectionChange = (selection: any) => {
  // selectedRows.value = selection;
};
const RowClick = (row, selection) => {
  if (row.id == 1) {
    parentIdValue.value[0] = 1;
    formAsid.value.parentId = 1;
  } else {
    const parentIds = getparentIds(row.parentId);
    parentIdValue.value = parentIds;
    formAsid.value.parentId = parentIds[parentIds.length - 1];
  }
  formAsid.value.status = row.status == "启用" ? true : false;
  formAsid.value.level = row.level;
  formAsid.value.id = row.id;
  formAsid.value.code = row.code;
  formAsid.value.name = row.name;
  formAsid.value.description = row.description;
  showInsertButton.value = false;
};
const rowState = (arg) => {
  return {
    height: "20px", // 设置合适的行高值
    fontSize: "12px", // 设置合适的字体大小值
    // color: "black",
  };
};
const dynamicHeightYtfl = ref(null);
const dynamicHeight = ref(null);
const screenHeight = ref(null);

const getScreenHeight = () => {
  dynamicHeight.value = `${window.innerHeight - 111}`;
  screenHeight.value = window.innerHeight - 146;
};
getScreenHeight();
const treeRef = ref<InstanceType<typeof ElTree>>();
const filterText = ref("");
watch(filterText, (val) => {
  treeRef.value!.filter(val);
});
const filterNode = (value: string, data: Tree) => {
  if (!value) return true;
  return data.label.includes(value);
};

interface Tree {
  label: string;
  children?: Tree[];
}

const handleNodeClick = async (data: Tree) => {
  try {
    const res = await crud.fetchData(
      "/select/ParameterClassification/Aside/All",
      "post",
      { parentID: data.id }
    );
    console.log(res);
    total.value = 0;
    tableData.value = res;
  } catch (error) {
    console.error("请求失败:", error);
  }
  for (let i = 0; i < tableData.value.length; i++) {
    if (tableData.value[i].id == data.parentID) {
      // 当前节点的父级内容
      var matchedNode = tableData.value[i];
      break;
    }
  }
  if (matchedNode == null) {
    parentIDValue.value[0] = 1;
    formAsid.value.parentID = 1;
  } else {
    const ids = getParentIds(data.parentID);
    parentIDValue.value = ids;
    formAsid.value.parentID = matchedNode.id;
  }
  formAsid.value.status = data.status == 1 ? true : false;
  formAsid.value.level = data.level;
  formAsid.value.id = data.id;
  formAsid.value.code = data.code;
  formAsid.value.name = data.name;
  formAsid.value.description = data.description;
  showInsertButton.value = false;
};
const getparentIds = (nodeId) => {
  const parentIds = [];
  let currentNode = tableData.value.find((node) => node.id === nodeId);
  while (currentNode && currentNode.parentId !== null) {
    parentIds.push(currentNode.id);
    currentNode = tableData.value.find((node) => node.id === currentNode.parentId);
  }

  return parentIds.reverse();
};
const data: ref<Tree[]> = ref([]);
const parentIdOptions = ref([]);

const defaultProps = {
  children: "children",
  label: "label",
};

const requestData = computed(() => ({}));
const transformResToOption = (data) => {
  const transform = (items) => {
    return items.map((item) => ({
      value: item.id,
      label: item.name,
      level: item.level,
      children: item.children ? transform(item.children) : [],
    }));
  };

  return transform(data);
};
const selectBusinessMatterClassificationAside = async () => {
  try {
    const res = await crud.fetchData(
      "/select/ParameterClassification/Aside",
      "post",
      requestData.value
    );
    data.value = res;
    const transformedRes = transformResToOption(res);
    parentIdOptions.value = transformedRes;
  } catch (error) {
    console.error("请求失败:", error);
  }
};

const selectBusinessDate = computed(() => ({
  page: page.value,
  limit: limit.value,
}));
const selectBusinessMatterClassification = async () => {
  loading.value = true;
  try {
    const res = await crud.fetchData(
      "/select/ParameterClassification",
      "post",
      selectBusinessDate.value
    );
    if (res.length == 0) {
      total.value = 0;
      loading.value = false;
      return;
    }
    const definitionsList = res;
    total.value = definitionsList[0].total;
    loading.value = false;

    tableData.value = definitionsList.map((item: any) => ({
      status: item.status === 1 ? "启用" : item.status === 0 ? "未启用" : "停用",
      id: item.id,
      code: item.code,
      name: item.name,
      description: item.description,
      level: item.level,
      parentId: item.parentId,
      isLeaf: item.isLeaf === 0 ? "否" : "是",
    }));
  } catch (error) {
    loading.value = false;
    console.error("请求失败:", error);
  }
};
const handleSizeChange = (val: number) => {
  selectBusinessMatterClassification();
};
const handleCurrentChange = (val: number) => {
  selectBusinessMatterClassification();
};
selectBusinessMatterClassificationAside();
selectBusinessMatterClassification();
const parentIdValue = ref([]);
const props = {
  checkStrictly: true,
};
const findLevelByValue = (options, targetValue) => {
  for (const option of options) {
    // 如果当前选项的值与目标值匹配，则返回该选项的级别
    if (option.value === targetValue) {
      return option.level;
    }
    // 如果当前选项有子选项，则递归调用该函数
    if (option.children && option.children.length > 0) {
      const level = findLevelByValue(option.children, targetValue);
      // 如果在子选项中找到了目标值，则返回找到的级别
      if (level !== undefined) {
        return level;
      }
    }
  }
  // 如果未找到目标值，则返回 undefined
  return undefined;
};

const handleChange = (value) => {
  if (value == null) {
    formAsid.value.level = "";
    return;
  }
  const selectedValue = value[value.length - 1];
  formAsid.value.parentId = selectedValue;
  const level = findLevelByValue(parentIdOptions.value, selectedValue);
  if (level !== undefined) {
    formAsid.value.level = level + 1;
  } else {
    formAsid.value.level = -1;
  }
};
const clearFormAsid = () => {
  for (const key of Object.keys(formAsid.value)) {
    if (typeof formAsid.value[key] === "string") {
      formAsid.value[key] = "";
    } else if (typeof formAsid.value[key] === "boolean") {
      formAsid.value[key] = false;
    } else if (typeof formAsid.value[key] === "number") {
      formAsid.value[key] = ""; // 或者设置为默认值
    } else if (Array.isArray(formAsid.value[key])) {
      formAsid.value[key] = []; // 清空数组
    } else {
      // 其他类型的属性，根据需要进行处理
    }
  }
};
const inseartAdminUser = () => {
  showInsertButton.value = true;
  parentIdValue.value = "";
  clearFormAsid();
};
</script>

<style scoped>
.el-table {
  /* --el-table-row-hover-bg-color: rgba(0, 158, 250, 0.219) !important; */
  /* --el-table-row-hover-bg-color: #fef5f0 !important; */
  --el-table-row-hover-bg-color: rgba(254, 245, 240, 0.8) !important;
}
/* 选中 */
.el-table {
  /* --el-table-row-hover-bg-color: #fef5f0 !important; */
  --el-table-row-hover-bg-color: rgba(254, 245, 240, 0.8) !important;
}
.down-tree ::v-deep .el-tree-node.is-expanded > .el-tree-node__children {
  display: inline;
}
.down-tree {
  height: 100%;
}
.demo-pagination-block {
  float: right;
}
.custom-dialog {
  position: fixed;
  top: 10em;
  left: 50%;
  width: 20%;
  /* 其他样式... */
}
</style>
